const express = require('express')
const OAuth = require('wechat-oauth')
const app = express()
const config = require('./config')
const parseConfig = config.parse
const wecahtConfig = config.wechat
const wechatServer = config.wechatServer
const client = new OAuth(wecahtConfig.appid, wecahtConfig.appsecret)

const Parse = require('parse/node')
// 启动parse-server
Parse.initialize(parseConfig.appId, parseConfig.javascriptKey)
Parse.serverURL = parseConfig.serverURL

app.use('/wxauth', (req, res) => {
  const url = client.getAuthorizeURL(`${wechatServer.authServer}/link-user`, '', 'snsapi_userinfo')
  res.redirect(url)
})

app.use('/link-user', async (req, res) => {
  const { code } = req.query
  client.getAccessToken(code, (err, result) => {
    if (err) {
      console.log(err)
      return res.status(500).end()
    }
    const accessToken = result.data.access_token
    const openid = result.data.openid
    client.getUser({openid: openid, lang: 'zh_CN'}, async (err, result) => {
      if (err) {
        console.log(err)
        return res.status(500).end()
      }
      if (result && result.openid) {
        await Parse.Cloud.run('createWechatUser', result)
        res.redirect(`${wechatServer.authRedirect}?openid=${result.openid}&access_token=${accessToken}`)
      }
    })
  })
})

app.listen(wechatServer.port, function () {
  console.log(`wechat running on port ${wechatServer.port}.`)
})
